﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GAIA_Logica;

namespace GAIA_IU
{
    public partial class CensoUI : System.Web.UI.Page
    {
        private List<Terreno> listaTerrenos = new List<Terreno>();
        private Terreno terreno = new Terreno();
        private Estudio estudio;

        protected void Page_Load(object sender, EventArgs e)
        {
            bool login = Session["login"] != null ? Boolean.Parse(Session["login"].ToString()) : false;

            if (login)
            {

                if (IsPostBack)
                {

                }
                else
                {
                    Session["codigo_cliente"] = Request["idCliente"];
                }
            }
            else {
                Response.Redirect("Login.aspx");
            }
        }

        protected void btn_busqueda_Click(object sender, EventArgs e)
        {
            string param_option = tipo_busqueda.SelectedValue;
            string param = txt_busqueda.Text;
            Terreno terrenoTemp = new Terreno();;
            try
            {
                switch (param_option)
                {
                    case "nombre":
                        listaTerrenos = terrenoTemp.buscarXNombre(param);
                        break;
                    case "id":
                        terrenoTemp.getTerreno(int.Parse(param));
                        listaTerrenos.Add(terrenoTemp);
                        break;
                }
                cargarDatos();
                GridView_Parcelas.DataSource = null;
                GridView_Parcelas.DataBind();
                GridView_Parcelas.CssClass = "unloaded";
                /*xxxxx*/
            }
            catch (Exception ex)
            {
                Avisar("Error al buscar al cliente. Por favor intente nuevamente. (" + ex.Message + ")", false);
            }
        }

        protected void Avisar(string aviso, bool resultado)
        {
            aviso_label.Text = aviso;
            if (resultado)
            {
                aviso_label.CssClass = "_true";
            }
            else
            {
                aviso_label.CssClass = "_false";
            }

        }

        protected void ClearForm()
        {
            txt_busqueda.Text = "";
            /*txt_apellido2.Text = "";
            txt_id.Text = "";
            txt_nombre.Text = "";*/
            GridView_Terrenos.DataSource = null;
            GridView_Terrenos.DataBind();
            //
            GridView_Parcelas.DataSource = null;
            GridView_Parcelas.DataBind();
            GridView_Parcelas.CssClass = "unloaded";
        }

        protected void cargarDatos(){

            GridView_Terrenos.DataSource = listaTerrenos;
            GridView_Terrenos.DataBind();
            Session["ListaDeTerrenos"] = listaTerrenos;
        }

        protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView_Terrenos.DataSource = (List<Terreno>)Session["ListaDeTerrenos"];
            GridView_Terrenos.PageIndex = e.NewPageIndex;
            GridView_Terrenos.DataBind();
        }


        protected void btn_salvar_Click(object sender, EventArgs e)
        {
            
            string id_cliente = (String)Session["codigo_cliente"];
            int id_parcela = (Int32)Session["id_segemento"];
            try
            {

                estudio = new Estudio(id_cliente, id_parcela);
                estudio.ingrearEstudio();
                if (insertarElementos(estudio.CodEstudio))
                {
                    Avisar("Un nuevo estudio de terreno ha sido ingresado al sistema", true);
                }
                else
                {
                    Avisar("Error al ingresar el estudio. Por favor intente nuevamente", false);
                }

                ClearForm();
            }
            catch (Exception ex)
            {
                Avisar("Error al ingresar el estudio. Por favor intente nuevamente :(" + ex.Message + ")", false);
            }

        }

        
        protected bool insertarElementos(int cod_estudio)
        {
            bool result = false;
            //List<GAIA_Logica.Segmento> listaSegmentos;
            GAIA_Logica.Elemento tempElemento;
            int cant_especies = int.Parse(Request["cant_especies"]);
            try
            {
                for (int x = 0; x < cant_especies; x++)
                {
                    if (Request["especies[" + x + "].dap"] != null)
                    {
                        int pid_especie = int.Parse(Request["especies[" + x + "].id"]);

                        string _db_DAP = (Request["especies[" + x + "].dap"]);
                        string db_DAP = _db_DAP.Replace(".", ",");
                        double pDap = double.Parse(db_DAP);

                        string _db_HC = (Request["especies[" + x + "].hc"]);
                        string db_HC = _db_HC.Replace('.', ',');
                        double pHc = double.Parse(db_HC);

                        string _db_volumen = (Request["especies[" + x + "].calculo"]);
                        string db_volumen = _db_volumen.Replace('.', ',');
                        double pVolumen = double.Parse(db_volumen);

                        string _db_arebasal = (Request["especies[" + x + "].areabasal"]);
                        string db_arebasal = _db_arebasal.Replace('.', ',');
                        double pAreaBasal = double.Parse(db_arebasal);


                        string _lambertN = (Request["especies[" + x + "].lambertN"]);
                        string lambertN = _lambertN.Replace('.', ',');
                        double pLambertN = double.Parse(lambertN);

                        string _lambertE = (Request["especies[" + x + "].lambertE"]);
                        string lambertE = _lambertE.Replace('.', ',');
                        double pLambertE = double.Parse(lambertE);

                        pLambertE = getMinDec(pLambertE);
                        pLambertN = getMinDec(pLambertN);

                        double crtm05N = getCrmt05N(pLambertN,pLambertE);
                        double crtm05E = getCrmt05E(pLambertN,pLambertE);

                        tempElemento = new Elemento(pDap, pHc, pVolumen, pAreaBasal, pid_especie, cod_estudio,pLambertN,pLambertE,crtm05N,crtm05E);
                        result = tempElemento.ingresaElemento();
                    }
                }
            }
            catch (Exception ex)
            {
                Avisar("Error al ingresar las parcelas. Por favor intente nuevamente :(" + ex.Message + ")", false);
                result = false;
            }
            return result;
        }

        protected void GridView_Terrenos_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id_terreno = (Int32)GridView_Terrenos.SelectedDataKey.Values["Id"];
            string nombre_terreno = (String)GridView_Terrenos.SelectedDataKey.Values["Nombre"];
            List<Segmento> listaParcelas = new List<Segmento>();
            Segmento tmp_parcela = new Segmento();
            listaParcelas = tmp_parcela.getListaSegmentosTerreno(id_terreno);
            GridView_Parcelas.DataSource = listaParcelas;
            GridView_Parcelas.DataBind();
        }

        protected void GridView_Parcelas_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<Especies> listaEspecies = new List<Especies>();
            Especies tmp_especie = new Especies();
            listaEspecies = tmp_especie.getListaEspecies();
            Session["id_segemento"] = (Int32)GridView_Parcelas.SelectedDataKey.Values["Id"];
            rptPlants.DataSource = listaEspecies;
            rptPlants.DataBind();
            GridView_Parcelas.CssClass = "loaded";
        }


        //Obtiene crmt05N apartir de lambert norte ye 
        private double getCrmt05N(double nl, double el) {
            double result = 0.0;
			
			double fe=500000.0;
			double e = (el - fe) * 0.00001;
			
			if(nl>0 && el>0){
				double fn = 271820.52;
				double n = (nl - fn) * 0.00001;
				double a00 = 1156874.11;
				double a10 = 99964.18;
				double a01 = -105.22;
				double a20 = -0.01;
				double a11 = -8.97;
				double a30 = -4.15;
				double a21 = 0.03;
				double a12 = 12.37;
				double a03 = 0;
				double b00 = 463736.66;
				double b10 = 105.19;
				double b01 = 99964.19;
				double b20 = 4.49;
				double b02 = -4.49;
				double b21 = -12.39;
				double b12 = 0.03;
				double b03 = 4.12;
				
				double n90 = a00 + a10 * n + a01 * e + a20 * n * n + a11 * n * e + a30 * n * n * n + a21 * n * n * e + a12 * n * e * e + a03 * e * e * e;
				double e90 = b00 + b10 * n + b01 * e + b20 * n * n + b02 * e * e + b21 * n * n * e + b12 * n * e * e + b03 * e * e * e;
				
				if (!((n90 < 1056672 || n90 > 1237077) || (e90 < 283690 || e90 > 663760)))
				{
					double a0 = -7.75237044;
					double b0 = -3.525688428;
					double a1 = 1.00000086635;
					double b1 = -0.00000000018;
					double n98 = a0 + a1 * n90 - b1 * e90;
					double e98 = b0 + a1 * e90 + b1 * n90;
					 a0 = -0.179913184;
					 b0 = -149.644487588;
					 a1 = 1.00030018487;
					 b1 = -0.00000034731;
					result = a0 + a1 * n98 - b1 * e98;
				
				}

			}

            result = getMinDec(result);
            return result;
        }

        private double getCrmt05E(double nl, double el)
        {
            double result = 0.0;

            double fe = 500000.0;
            double e = (el - fe) * 0.00001;
			
			
			if(nl>0 && el>0){
				double fn = 271820.52;
				double n = (nl - fn) * 0.00001;
				double a00 = 1156874.11;
				double a10 = 99964.18;
				double a01 = -105.22;
				double a20 = -0.01;
				double a11 = -8.97;
				double a30 = -4.15;
				double a21 = 0.03;
				double a12 = 12.37;
				double a03 = 0;
				double b00 = 463736.66;
				double b10 = 105.19;
				double b01 = 99964.19;
				double b20 = 4.49;
				double b02 = -4.49;
				double b21 = -12.39;
				double b12 = 0.03;
				double b03 = 4.12;
				
				double n90 = a00 + a10 * n + a01 * e + a20 * n * n + a11 * n * e + a30 * n * n * n + a21 * n * n * e + a12 * n * e * e + a03 * e * e * e;
				double e90 = b00 + b10 * n + b01 * e + b20 * n * n + b02 * e * e + b21 * n * n * e + b12 * n * e * e + b03 * e * e * e;
				
				if (!((n90 < 1056672 || n90 > 1237077) || (e90 < 283690 || e90 > 663760)))
				{
					double a0 = -7.75237044;
					double b0 = -3.525688428;
					double a1 = 1.00000086635;
					double b1 = -0.00000000018;
					double n98 = a0 + a1 * n90 - b1 * e90;
					double e98 = b0 + a1 * e90 + b1 * n90;
					a0 = -0.179913184;
					b0 = -149.644487588;
					a1 = 1.00030018487;
					b1 = -0.00000034731;
					result = b0 + a1 * e98 + b1 * n98;
				
				}

			}

            result = getMinDec(result);
            return result;
        }

        private double getMinDec(double value) {
            value = Math.Truncate(value * 1000) / 1000;
            //double result = Math.Round(value, 2, MidpointRounding.AwayFromZero);
            return value;
        }
    
    }    
}